import subprocess
import json
from typing import Dict, Optional, Union

from WebBackend.dataclass.DiskItem import SMART_Attributes


def get_disk_smart_info(device_path: str) -> SMART_Attributes:
    # 基础返回结构（确保始终有默认值）
    smart_result = {
        "smart_available": False,
        "attributes": {}
    }

    try:
        cmd = ["smartctl", "-i", "-A", "-H", "--json", device_path]
        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
        if proc.returncode != 0:
            return smart_result

        data = json.loads(proc.stdout)
        smart_result.update({'smart_available': True})
        # 基本信息
        smart_attr = {
            "_model": data.get("model_name", "Unknown").strip(),
            "_serial": data.get("serial_number", "Unknown").strip(),
            "_health": "PASSED" if data.get("smart_status", {}).get("passed") else "FAILED",
            "_temperature": data.get("temperature", {}).get("current"),
            "_rotation_rate": int(data["rotation_rate"]) if data.get("rotation_rate") not in (
                None, "Solid State Device") else None
        }

        # 处理 SMART 属性表（按要求的格式）
        if "ata_smart_attributes" in data:
            for attr in data["ata_smart_attributes"].get("table", []):
                name = attr.get("name", "").strip()
                if name:
                    # 将属性ID转换为十六进制（2位大写，如 '0E'）
                    attr_id = f"{attr.get('id', 0):02X}"
                    # 按要求的格式存储属性
                    smart_attr[name] = {
                        "id": attr_id,
                        "text": computed_language_text(name),  # 可根据需要添加描述
                        "value": str(attr.get("raw", {}).get("value", ""))
                    }

        smart_result["attributes"] = smart_attr

    except (json.JSONDecodeError, subprocess.TimeoutExpired, KeyError, ValueError) as e:
        # 更具体的异常捕获
        pass  # 保持默认返回值

    return smart_result


def computed_language_text(text: str = '') -> str:
    """
    返回常见SMART属性的中文描述文本。
    如果属性未知，返回空字符串。
    """
    smart_attribute_descriptions = {
        # 原有属性保留
        "Reallocated_Sector_Ct": "重分配扇区数",
        "Power_On_Hours": "硬盘通电时长",
        "Power_Cycle_Count": "通电周期次数",
        "Temperature_Celsius": "当前温度",
        "Reported_Uncorrect": "未纠正错误数",
        "Current_Pending_Sector": "待重分配扇区数",
        "Offline_Uncorrectable": "离线不可纠正错误数",
        "Raw_Read_Error_Rate": "原始读取错误率",
        "Seek_Time_Performance": "寻道时间性能",
        "Calibration_Retry_Count": "校准重试次数",
        "Command_Timeout": "命令超时次数",
        "High_Fly_Writes": "飞行高度写入次数",
        "Airflow_Temperature_Cel": "气流温度",
        "G-Sense_Error_Rate": "加速度错误率",
        "Power-Off_Retract_Count": "断电磁头复位次数",
        "Load_Cycle_Count": "磁头加载周期数",
        "Hardware_ECC_Recovered": "硬件ECC恢复数",
        "Reallocated_Event_Count": "重分配事件计数",
        "Current_Pending_ECC_Cnt": "待处理ECC计数",
        "UDMA_CRC_Error_Count": "UDMA CRC错误数",
        "Multi_Zone_Error_Rate": "多区域错误率",
        "Percent_Lifetime_Remain": "剩余寿命百分比",
        "Head_Flying_Hours": "磁头飞行时长",
        "Total_LBAs_Written": "总写入LBA数",
        "Total_LBAs_Read": "总读取LBA数",
        "Write_Error_Rate": "写入错误率",
        "Success_RAIN_Recov_Cnt": "成功RAIN恢复次数",
        "Available_Reservd_Space": "可用保留空间",
        "Host_Program_Page_Count": "主机编程页数",
        "FTL_Program_Page_Count": "FTL编程页数",
        "Program_Fail_Count": "编程失败计数",
        "Erase_Fail_Count": "擦除失败计数",
        "Ave_Block-Erase_Count": "平均块擦除次数",
        "Unexpect_Power_Loss_Ct": "意外断电次数",
        "Unused_Reserve_NAND_Blk": "未使用NAND备用块",
        "SATA_Interfac_Downshift": "SATA接口降速次数",
        "Error_Correction_Count": "错误校正计数",
        
        # 新增属性
        "Throughput_Performance": "吞吐性能",
        "Spin_Up_Time": "盘片启动时间",
        "Start_Stop_Count": "启停次数",
        "Reallocate_NAND_Blk_Cnt": "重分配NAND块数",
        "Seek_Error_Rate": "寻道错误率",
        "Spin_Retry_Count": "盘片启动重试次数",
        "Runtime_Bad_Block": "运行时坏块数",
        "End-to-End_Error": "端到端错误",
        "Read_Soft_Error_Rate": "读取软错误率",
        "Unknown_Attribute": "未知属性",
        "Unused_Rsvd_Blk_Cnt_Tot": "未使用备用块总数",
        "Program_Fail_Cnt_Total": "编程失败总次数",
        "Runtime_Bad_Block": "运行时坏块数"  # 重复项保持相同翻译
    }
    
    return smart_attribute_descriptions.get(text, "")


if __name__ == "__main__":
    print(get_disk_smart_info("/dev/sda"))
